package org.xtremeobjects.domain.hibernate;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.xtremeobjects.domain.model.ddd.GenericRepository;

import com.google.inject.Inject;

public class HibernateRepository<E extends Object, PK> implements GenericRepository<E, PK> {

	private HibernateSession session;
	
	protected Session getSession() {
		if(session==null)
			throw new RuntimeException("Session should be injected before this object can be used.");
		return session.getSession();
	}
	
	/**
	 * Session should be injected before this object can be used.
	 * @param session
	 */
	public void setSession( HibernateSession session ) {
		this.session = session;
	}

	@Inject
	protected HibernateRepository( HibernateSession session ) {
		this.session = session;
	}

	public List<E> allInstances() {
		return (List<E>) getSession().createCriteria(getEntityClass()).list();
	}

	public E findById(PK id) {
		return (E) getSession().createCriteria(getEntityClass()).add(
				Restrictions.eq("id", id)).uniqueResult();
	}

	/**/

	public void add(Collection<E> anObjectCollection) {
		try {
			Transaction transaction = getSession().beginTransaction();
			for (E anObject : anObjectCollection) {
				getSession().saveOrUpdate(anObject);
			}
			transaction.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void add(E anObject) {
		try {
			Transaction transaction = getSession().beginTransaction();
			getSession().saveOrUpdate(anObject);
			transaction.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void remove(E anObject) {
		try {
			Transaction transaction = getSession().beginTransaction();
			getSession().delete(anObject);
			transaction.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void remove(Collection<E> anObjectCollection) {
		try {
			Transaction transaction = getSession().beginTransaction();
			for (E anObject : anObjectCollection) {
				getSession().delete(anObject);
			}
			transaction.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void update(E anObject) {
		try {
			Transaction transaction = getSession().beginTransaction();
			getSession().saveOrUpdate(anObject);
			transaction.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void update(Collection<E> anObjectCollection) {
		try {
			Transaction transaction = getSession().beginTransaction();
			for (E anObject : anObjectCollection) {
				getSession().saveOrUpdate(anObject);
			}
			transaction.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private Class _entityClass;

	protected synchronized Class getEntityClass() {

		if (_entityClass == null) {
			Type type = getClass().getGenericSuperclass();
			loop: while (true) {
				if (type instanceof ParameterizedType) {
					Type[] arguments = ((ParameterizedType) type)
							.getActualTypeArguments();
					for (Type argument : arguments) {
						if (argument instanceof Class
						/*******************************************************
						 * && DatabaseObject.class.isAssignableFrom( //Check if
						 * an entity ((Class)argument)) /
						 ******************************************************/
						) {
							_entityClass = (Class) argument;
							break loop;
						}
					}
				}
				if (type != null) {
					type = ((Class) type).getGenericSuperclass();
					if (type == Object.class) {
						throw new RuntimeException("Could not find an entity "
								+ "subclass parameterized type");
					}
				} else
					break;
			}
		}
		return _entityClass;
	}

	public void addObject(Object anObject) {
		add((E) anObject);
	}

	public void addObject(Collection anObjectCollection) {
		add((Collection<E>) anObjectCollection);
	}

	public Object findObjectById(String anId) {
		return findById((PK) anId);
	}

	public void removeObject(Object anObject) {
		remove((E) anObject);
	}

	public void removeObject(Collection anObjectCollection) {
		remove((Collection<E>) anObjectCollection);
	}

	public void updateObject(Object anObject) {
		update((E) anObject);
	}

	public void updateObject(Collection anObjectCollection) {
		update((Collection<E>) anObjectCollection);
	}

	public boolean canAdd() {
		return true;
	}

	public boolean canRemove() {
		return true;
	}
}
